package com.aua.book.android.xml;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Paint;
import android.graphics.Rect;
import android.util.DisplayMetrics;

public class PageCreator {

  private static int getNumOfChars(AndroidBookActivity app, float myTextSize,String str) {
    
   DisplayMetrics displaymetrics = new DisplayMetrics();
    app.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int displaysHeight = displaymetrics.heightPixels;
    int displaysWidth = displaymetrics.widthPixels;
      
  //change 48 on textviews top
    int viewsHeight=displaysHeight-48;
       
    Paint paint = new Paint();
    paint.setTextSize(myTextSize); // Your text size
    
    Rect bounds = new Rect();
    paint.getTextBounds("a", 0, 1, bounds); 
    Paint.FontMetrics m=paint.getFontMetrics();
    int textHeight =(int) m.bottom-(int)m.top;     
    int rows=viewsHeight/(textHeight); 
    int numCharsW = paint.breakText(app.getBookText(), true, displaysWidth, null);     
   return numCharsW*rows;
   // return 300;

  }

  public static void creat(AndroidBookActivity app, float strSize) {
    List<String> pages =  new ArrayList<String>();
    String str=app.getBookText();
    int i, numOfChars = getNumOfChars(app, strSize,str);
    int k=0;
    for (i = 0;  i + numOfChars < str.length(); i += numOfChars) {
      if(str.charAt(i+numOfChars) != ' ')     
        while(str.charAt(i+numOfChars-k) != ' ')
           k++;
        
      pages.add(str.substring(i, i + numOfChars-k));
      i-=k;
      k=0;
    }
    pages.add(str.substring(i, str.length()));
    app.setPages(pages);    
    app.setLastPage(pages.size());
    app.setCurrentSize(strSize);
  }

}
